import HouseFormModal from '@/components/HouseFormModal';
import { exposeHouse, getHouseList, hideHouse } from '@/services/house-list';
import { HouseItem } from '@/types/house';
import type { ActionType } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Button, Form, Tooltip } from 'antd';
import React, { useRef, useState } from 'react';
import { handleProTableRequest, callApi } from '@/utils/request';
import AuthorizedButton from '@/components/AuthorizedButton';

export default () => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>(null);
  const [activeKey, setActiveKey] = useState<React.Key | undefined>('all');

  // 房屋信息表单弹窗状态
  const [houseFormModalVisible, setHouseFormModalVisible] = useState(false);

  // 曝光操作
  const handleExpose = async (id: string) => {
    const result = await callApi(
        () => exposeHouse(id),
        { successMsg: '曝光成功', errorMsg: '曝光失败' }
    );

    if (result) {
      actionRef.current?.reload();
    }
  };

  // 隐藏操作
  const handleHide = async (id: string) => {
    const result = await callApi(
        () => hideHouse(id),
        { successMsg: '隐藏成功', errorMsg: '隐藏失败' }
    );

    if (result) {
      actionRef.current?.reload();
    }
  };

  // 设置信息操作
  const handleSetRentalInfo = (id: string) => {
    // 跳转到出租信息表单页面
    history.push(`/house_manage/rental_form?id=${id}`);
  };

  const handleSetPropertyInfo = (id: string) => {
    console.log('设置产权信息:', id);
  };

  const handleSetAuthInfo = (id: string) => {
    console.log('设置核验信息:', id);
  };

  // 渲染操作按钮
  const renderActions = (item: HouseItem) => {
    const actions = [
      <a
          key="view"
          onClick={() => history.push(`/house_manage/detail/${item.id}`)}
      >
        查看
      </a>,
    ];

    // 设置产权信息按钮
    if (!item.hasPropertyInfo) {
      actions.push(
          <AuthorizedButton
              key="setProperty"
              code="house_list_set_property_btn" // 替换为实际权限码
              type="link"
              size="small"
              onClick={() => handleSetPropertyInfo(item.id)}
          >
            填写产权
          </AuthorizedButton>,
      );
    } else if (!item.hasAuthInfo) {
      // 设置核验信息按钮
      actions.push(
          <AuthorizedButton
              key="setAuth"
              code="house_list_set_auth_btn" // 替换为实际权限码
              type="link"
              size="small"
              onClick={() => handleSetAuthInfo(item.id)}
          >
            上传核验
          </AuthorizedButton>,
      );
    } else if (!item.hasRentalInfo) {
      // 设置出租信息按钮
      actions.push(
          <AuthorizedButton
              key="setRental"
              code="house_list_set_rental_btn" // 替换为实际权限码
              type="link"
              size="small"
              onClick={() => handleSetRentalInfo(item.id)}
          >
            填写出租信息
          </AuthorizedButton>,
      );
    }

    // 曝光/隐藏按钮
    if (item.hasPropertyInfo && item.hasAuthInfo && item.hasRentalInfo) {
      if (item.isExposed) {
        actions.push(
            <AuthorizedButton
                key="hide"
                code="house_list_hide_btn" // 替换为实际权限码
                type="link"
                size="small"
                danger
                onClick={() => handleHide(item.id)}
            >
              隐藏
            </AuthorizedButton>,
        );
      } else {
        actions.push(
            <AuthorizedButton
                key="expose"
                code="house_list_expose_btn" // 替换为实际权限码
                type="link"
                size="small"
                onClick={() => handleExpose(item.id)}
            >
              曝光
            </AuthorizedButton>,
        );
      }
    } else {
      actions.push(
          <Tooltip
              key="expose-disabled"
              title={
                !item.hasPropertyInfo
                    ? '没有产权信息'
                    : !item.hasAuthInfo
                        ? '没有核验信息'
                        : '没有出租信息'
              }
          >
            <Button type="link" size="small" disabled>
              曝光
            </Button>
          </Tooltip>,
      );
    }

    return actions;
  };

  return (
      <PageContainer
          header={{
            title: '',
          }}
      >
        {/* ProTable 表格形式的列表 */}
        <ProTable<HouseItem>
            rowKey="id"
            actionRef={actionRef}
            search={false}
            request={async (params, sort, filter) => {
              const formValues = form.getFieldsValue();
              const sortBy = Object.keys(sort)[0] as
                  | 'signDate'
                  | 'expireDate'
                  | 'exposure'
                  | 'clicks'
                  | 'inquiries'
                  | 'monthlyRent'
                  | undefined;
              const order = sort[sortBy!] === 'ascend' ? 'ascend' : 'descend';

              const queryParams = {
                ...formValues,
                tab: activeKey,
                current: params.current,
                pageSize: params.pageSize,
                cityName: params.cityName,
                communityName: params.communityName,
                sortBy,
                order,
              };

              return handleProTableRequest<HouseItem>(
                  () => getHouseList(queryParams),
                  { errorMsg: '获取房屋列表失败' }
              );
            }}
            scroll={{ x: 'max-content' }}
            columns={[
              {
                title: '城市',
                dataIndex: 'cityName',
                fixed: 'left',
                width: 70,
                ellipsis: true,
              },
              {
                title: '小区名称',
                dataIndex: 'communityName',
                fixed: 'left',
                width: 120,
                ellipsis: true,
                onCell: () => ({
                  style: {
                    maxWidth: 120,
                  },
                }),
              },
              {
                title: '房屋信息',
                dataIndex: 'houseInfo',
                fixed: 'left',
                width: 120,
                render: () => '7栋3单元1502',
                ellipsis: true,
                onCell: () => ({
                  style: {
                    maxWidth: 120,
                  },
                }),
              },
              {
                title: '地址',
                dataIndex: 'address',
                width: 200,
                ellipsis: true,
                onCell: () => ({
                  style: {
                    maxWidth: 200,
                  },
                }),
              },
              {
                title: '产权面积',
                dataIndex: 'area',
                render: (text) => (text ? `${text}㎡` : '-'),
                width: 100,
                sorter: true,
                search: false,
              },
              {
                title: '入住率',
                dataIndex: 'occupancy',
                render: (_, record) =>
                    record.occupancy
                        ? `${record.occupancy.current}/${record.occupancy.total}`
                        : '-',
                width: 100,
                sorter: true,
                search: false,
              },
              {
                title: '月租金',
                dataIndex: 'monthlyRent',
                render: (_, record) =>
                    record.monthlyRent
                        ? `¥${record.monthlyRent.actual}/¥${record.monthlyRent.base}`
                        : '-',
                width: 150,
                sorter: true,
                search: false,
              },
              {
                title: '包租合同金额/季',
                dataIndex: 'contractAmount',
                render: (text) => (text ? `¥${text.toLocaleString()}` : '-'),
                width: 150,
                sorter: true,
                search: false,
              },
              {
                title: '服务费',
                dataIndex: 'serviceFee',
                render: (text) => (text ? `¥${text}` : '-'),
                width: 100,
                sorter: true,
                search: false,
              },
              {
                title: '签约时间',
                dataIndex: 'signDate',
                width: 120,
                sorter: true,
                search: false,
                ellipsis: true,
              },
              {
                title: '到期时间',
                dataIndex: 'expireDate',
                width: 120,
                sorter: true,
                search: false,
                ellipsis: true,
              },
              {
                title: '曝光量',
                dataIndex: 'exposure',
                render: (text) => (text ? text.toString() : '-'),
                width: 100,
                sorter: true,
                search: false,
              },
              {
                title: '点击量',
                dataIndex: 'clicks',
                render: (text) => (text ? text.toString() : '-'),
                width: 100,
                sorter: true,
                search: false,
              },
              {
                title: '咨询量',
                dataIndex: 'inquiries',
                render: (text) => (text ? text.toString() : '-'),
                width: 100,
                sorter: true,
                search: false,
              },
              {
                title: '操作',
                valueType: 'option',
                width: 240,
                fixed: 'right',
                render: (_, row) => renderActions(row),
              },
            ]}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: true,
              showTotal: (total, range) =>
                  `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
              pageSizeOptions: ['10', '20', '50', '100'],
            }}
            toolbar={{
              search: false,
              menu: {
                activeKey,
                items: [
                  {
                    key: 'all',
                    label: <span>全部房屋</span>,
                  },
                  {
                    key: 'full',
                    label: <span>满租</span>,
                  },
                  {
                    key: 'not_full',
                    label: <span>未满租</span>,
                  },
                ],
                onChange(key) {
                  setActiveKey(key);
                },
              },
              actions: [
                <AuthorizedButton
                    type="primary"
                    key="primary"
                    code="house_list_add_btn" // 替换为实际权限码
                    onClick={() => setHouseFormModalVisible(true)}
                >
                  新建房屋
                </AuthorizedButton>,
              ],
            }}
            tableLayout="fixed"
        />

        {/* 房屋信息表单弹窗 */}
        <HouseFormModal
            visible={houseFormModalVisible}
            onCancel={() => setHouseFormModalVisible(false)}
            onSuccess={() => {
              setHouseFormModalVisible(false);
              actionRef.current?.reload();
            }}
        />
      </PageContainer>
  );
};